package com.example.tencentdemo.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.tencentdemo.service.Impl.MessageImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/channel/group/{group_id}")
public class chatChannel implements
        ApplicationContextAware {
    /**
     {"sender_id": 发送者id, "group_id": 群聊id , "type": 文本/文件  , "message": 信息内容}
     **/
    // 用于存储每个群聊对应的会话列表
    private static final Map<String, List<Session>> groupSessionsMap = new ConcurrentHashMap<>();

    // 全局静态变量，保存 ApplicationContext
    private static ApplicationContext applicationContext;
    // 声明需要的 Bean
    private com.example.tencentdemo.service.Impl.MessageImpl MessageImpl;



    @OnOpen
    public void onOpen(Session session, @PathParam("group_id") String group_id) {
        System.out.println("WebSocket连接开始: " + session.getId() + ", 群聊ID : " + group_id);

        // 获取当前群聊对应的会话列表
        List<Session> groupSessions = groupSessionsMap.computeIfAbsent(group_id, k -> new ArrayList<>());
        // 将当前会话添加到会话列表中
        groupSessions.add(session);

        System.out.println(groupSessionsMap);
    }

    // 当收到消息时触发
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message: " + message);
        JSONObject jsonObject = JSON.parseObject(message);
        String groupId = jsonObject.getString("group_id");

        // 获取当前群聊对应的会话列表
        List<Session> groupSessions = groupSessionsMap.get(groupId);
        if (groupSessions != null) {
            // 向群聊中的所有会话发送消息
            for (Session groupSession : groupSessions) {
                sendMessageToSession(groupSession, message);
            }
        }
        // 存储到数据库
        this.MessageImpl = adminChannel.applicationContext.getBean(com.example.tencentdemo.service.Impl.MessageImpl.class);
        MessageImpl.insertMessage(com.example.tencentdemo.entity.group_message.fromJson(message));
    }

    // 辅助方法：发送消息给指定的会话
    private void sendMessageToSession(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket closed: " + session.getId());

        // 从所有群聊的会话列表中移除断开连接的会话
        for (List<Session> groupSessions : groupSessionsMap.values()) {
            groupSessions.remove(session);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        chatChannel.applicationContext = applicationContext;
    }
}